package user

import (
	"fmt"
	"gitee.com/libwiki/lib-mall/models/userModel"
	"gitee.com/libwiki/lib-mall/package/database"
	"gitee.com/libwiki/lib-mall/package/response"
	"github.com/go-oauth2/oauth2/v4"
	"github.com/go-oauth2/oauth2/v4/manage"
	"github.com/go-oauth2/oauth2/v4/models"
	"github.com/go-oauth2/oauth2/v4/store"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/net/ghttp"
)

var Auth = new(auth)

type auth struct{}

// Login 登录页面
func (a *auth) Login(r *ghttp.Request) {
	var user userModel.User
	res := database.Db().First(&user)
	if res.RowsAffected == 0 {
		response.Fail(r, "用户名或者密码错误")
	}
	//user.LastLoginTime = vars.Datetime(time.Now())
	//tx := database.Db().Updates(&user)
	//g.Dump(&user)

	response.JsonExit(r, 0, "ok", &user)
}

func (this *auth) Token(r *ghttp.Request) {
	manager := manage.NewDefaultManager()
	manager.SetClientTokenCfg(manage.DefaultPasswordTokenCfg)
	manager.SetRefreshTokenCfg(manage.DefaultRefreshTokenCfg)
	// token memory storeModel
	manager.MustTokenStorage(store.NewMemoryTokenStore())

	// client memory storeModel
	clientStore := store.NewClientStore()
	clientStore.Set("a", &models.Client{
		ID:     "name",
		Secret: "999999",
		Domain: "http://localhost",
	})
	manager.MapClientStorage(clientStore)

	tgr := &oauth2.TokenGenerateRequest{
		ClientID:     "a",
		ClientSecret: "999999",
		UserID:       "user_id_ini",
		Scope:        "all",
		Request:      r.Request,
	}
	ctx := r.Context()
	tokenInfo, err := manager.GenerateAccessToken(ctx, oauth2.ClientCredentials, tgr)
	if err != nil {
		fmt.Printf("errT:%T,errV:%v \n", err, err.Error())
		return
	}
	fmt.Printf("reToken:%v ExpiresIn:%v \n", tokenInfo.GetRefresh(), tokenInfo.GetAccessExpiresIn())
	info, _ := manager.GetClient(ctx, "a")

	tokenData, err := manager.LoadAccessToken(ctx, tokenInfo.GetAccess())
	if err != nil {
		fmt.Printf("tokenData errT:%T,errV:%V \n", err, err)
		return
	}

	refreshData, err := manager.LoadRefreshToken(ctx, tokenInfo.GetRefresh())
	if err != nil {
		fmt.Printf("refreshData errT:%T,errV:%V \n", err, err)
		return
	}
	response.Success(r, "ok", g.Map{
		"token":       tokenInfo,
		"client":      info,
		"tokenData":   tokenData,
		"refreshData": refreshData,
	}, "ok")
}
